package cn.doitedu.rtmk.demo.demo3;

import com.alibaba.fastjson.JSON;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.util.Collector;

public class RuleModel002Calculator {
    RuleModel002ParamBean ruleParamBean;

    public void init(String ruleParamJson) {
        ruleParamBean = JSON.parseObject(ruleParamJson, RuleModel002ParamBean.class);
    }


    public void calc(
            Demo3.EventBean eventBean,
            ValueState<Integer> valueState,
            Collector<Demo3.RtmkMessage> out
            ) throws Exception {

        /**
         * 一、进行规则所需要的实时画像标签的计算
         */
        // 实时画像条件：发生过 add_cart事件，且添加的商品的价格>200
        if (valueState.value() == null || valueState.value() == 0) {
            if (eventBean.getEventId().equals(ruleParamBean.getDynamicProfileEventId())
                    && Double.parseDouble(eventBean.getProperties().get(ruleParamBean.getDynamicProfilePropertyKey())) > ruleParamBean.getDynamicProfilePropertyValue()) {
                valueState.update(1);
            }
        }

        /**
         * 二、判断是否是预定义的营销规则的触发事件 ：加购事件（加购的商品价格>100)
         */

        if (eventBean.getEventId().equals(ruleParamBean.getFireEventId())) {
            System.out.println(eventBean.getUserId() + " 触发了规则002");

            // 判断该事件的行为人是否满足营销规则中定义的判断条件
            if (valueState.value() != null && valueState.value() == 1) {
                out.collect(new Demo3.RtmkMessage(eventBean.getUserId(), eventBean.getTimeStamp(), "rule002"));
            }

        }
    }
}
